<?php
/**
 * Created by xun at 2020/5/18
 */

namespace app\base;


use app\module\websocket\Chatee;
use app\storage\Config;
use app\storage\Singleton;

class CommandRunner
{

    use Singleton;

    public static function run($args)
    {
        $script_file = array_shift($args);
        $action = array_pop($args);
        $host = \app\storage\Config::getConfig('host');
        $port = \app\storage\Config::getConfig('port');
        $setting = \app\storage\Config::getConfig('settings.swoole');

        if ($action === 'start') {
            if (in_array('-d', $args)) {
                $setting['daemonize'] = 1;
                // echo '开始运行时间: ' . date('Y-m-d H:i:s') . PHP_EOL;
                // echo '运行模式: daemonize' . PHP_EOL;
                // echo '日志位置: app/logs/swoole.log' . PHP_EOL;
                echo '程序挂起就绪' . PHP_EOL;
                echo '日志查看位置: app/logs/swoole.log' . PHP_EOL;
            }
            // $server = new \app\module\websocket\Chatee($host, $port, $setting);
            $server = Chatee::getInstance($host, $port, $setting);
            $server->run();
        }

        if ($action === 'stop') {
            $pidFile = Config::getConfig('settings.swoole.pid_file');
            if (file_exists($pidFile)) {
                $pid = intval(file_get_contents($pidFile));
                if (!\swoole_process::kill($pid, 0)) {
                    echo "PID :{$pid} not exist \n";
                } else {
                    \swoole_process::kill($pid, SIGTERM);
                    echo "PID :{$pid} kill. \n";
                }
            }

        }

        if ($action === 'reload') {
            $pidFile = Config::getConfig('settings.swoole.pid_file');
            if (file_exists($pidFile)) {
                $pid = intval(file_get_contents($pidFile));
                if (in_array('-task', $args)) {
                    exec('kill -USR2 ' . $pid);
                } else {
                    exec('kill -USR1 ' . $pid);
                }
                echo 'reload pid: ' . $pid . ' success' . PHP_EOL;
            }
        }

    }
}